// pages/Album/Album.js
import request from '../../utils/request';
import PubSub from 'pubsub-js';

Page({
  data: {
    id: '',
    album: {},
    songlist: [],
    stats: {
      likedCount: 888,
      commentCount: 0,
      shareCount: 0,
    },
    currentIndex: 0, // 当前播放的歌曲索引
  },

  async onLoad(options) {
    try {
      const albumId = options.id;
      const res = await request(`/album?id=${albumId}`);
      if (!res || !res.album) throw new Error('API数据错误');

      this.setData({
        id: albumId,
        album: {
          name: res.album.name,
          picUrl: res.album.picUrl,
          artist: res.album.artists.map(ar => ar.name).join(' / '),
          artistPic: res.album.artist.img1v1Url,
          description: res.album.description || '暂无描述',
        },
        songlist: res.songs.map(song => ({
          id: song.id,
          name: song.name,
          artist: song.ar.map(ar => ar.name).join(' / '),
          duration: song.dt,
        })),
        stats: {
          likedCount: res.album.info.likedCount || 0,
          commentCount: res.album.info.commentCount || 0,
          shareCount: res.album.info.shareCount || 0,
        },
      });

      console.log('专辑数据加载成功:', this.data.album);
      console.log('歌曲列表数据:', this.data.songlist);
    } catch (error) {
      console.error('加载失败:', error);
      wx.showToast({ title: '加载失败', icon: 'none' });
    }

    // 订阅 switchType 事件
    PubSub.subscribe('switchType', (msg, type) => {
      this.handleSwitchSong(type); // 处理歌曲切换
    });
  },

  // 处理歌曲切换
  handleSwitchSong(type) {
    const { songlist, currentIndex } = this.data;
    let newIndex = currentIndex;

    if (type === 'prev') {
      newIndex = currentIndex === 0 ? songlist.length - 1 : currentIndex - 1; // 上一首
    } else if (type === 'next') {
      newIndex = currentIndex === songlist.length - 1 ? 0 : currentIndex + 1; // 下一首
    }

    this.setData({ currentIndex: newIndex }); // 更新当前索引
    const nextSongId = songlist[newIndex].id; // 获取下一首歌曲 ID
    wx.navigateTo({ url: `/pages/Song/Song?ids=${nextSongId}` }); // 跳转到新歌曲页面
  },

  // 跳转到歌曲页
  navigateToSong(event) {
    const songId = event.currentTarget.dataset.id;
    wx.navigateTo({ url: `/pages/Song/Song?ids=${songId}` });
  },

  // 跳转到评论页
  goToComment(event) {
    const songId = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/Comment/Comment?type=0&id=${songId}`
    });
  },
});